package com.xucia.persevere;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class PersevereCompiler extends com.xucia.strands.Compiler {
	public static void main(String[] args) throws IOException {
		if (args.length==0) {
			System.out.println("Usage: java -classpath lib/js-1.xRx.jar;lib/persevere.jar;js com.xucia.persevere.PersevereCompiler [OPTIONS]... [FILES]...\n" +
					"Compiles Persistent JavaScript files (.pjs) and JavaScript 1.7 (.js17) files to legacy JavaScript (.js)\n" +
					"	-a compile with auto save (orthogonal persistence) support (default for .pjs files)\n" +
					"	-m compile without auto save (orthogonal persistence) support (default for .js17 files)\n" +
					"	-d compile with original source included in comments (default)\n" +
					"	-c compile without original source included in comments\n" +
					"	-o output to standard out\n");
			return;
		}
		List<String> arguments = Arrays.asList(args);
		boolean outputToStrOut = arguments.indexOf("-o") != -1;
		for (String argument : arguments) {
			if (!argument.startsWith("-")) {
				boolean setters = (argument.endsWith(".pjs") && arguments.indexOf("-m") == -1) ||
					arguments.indexOf("-a") != -1;
				boolean debug = arguments.indexOf("-c") == -1;
				if (outputToStrOut)
					System.out.println(compileFile(argument,true,setters,debug));
				else {
					String outputFile = argument.replaceAll("\\.[^\\.]+\\z", ".js");
					if (outputFile.equals(argument))
						throw new RuntimeException("Will not replace files, compile files with a .pjs or .js17 extension or use the -o option to output to standard out");
					FileOutputStream ofs = new FileOutputStream(outputFile);
					ofs.write(compileFile(argument,true,setters,debug).getBytes());
					ofs.close();
				}
			}
		}
	}

}
